package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

public class BackWork2 extends Activity {
	TextView tv;
	ProgressDialog mProgress;
	AccumThread mThread;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.ch19_backwork);
		tv = (TextView) findViewById(R.id.ch19_backwork_tv);
	}

	public void mOnClick(View v) {
		int start = 0;
		int end = 100;
		
		mProgress = new ProgressDialog(this);
		mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgress.setTitle("Calculating");
		mProgress.setMessage("Wait...");
		mProgress.setCancelable(false);
		mProgress.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				mThread.mQuit = true;
				mProgress.dismiss();
			}
		});
		mProgress.show();
		
		mThread = new AccumThread(start, end, mAfterAccum);
		mThread.start();
		
	}
	
	Handler mAfterAccum = new Handler(){
		public void handleMessage(android.os.Message msg) {
			mProgress.dismiss();
			if(mThread.mQuit == false){
				tv.setText("" + mThread.mResult);
			}
		};
	};
	
	class AccumThread extends Thread{
		int mStart, mEnd;
		int mResult;
		Handler mAfter;
		boolean mQuit;
		
		public AccumThread(int mStart, int mEnd, Handler mAfter) {
			super();
			this.mStart = mStart;
			this.mEnd = mEnd;
			this.mAfter = mAfter;
			this.mQuit = false;
		}
		
		public void run() {
			mResult = 0;
			for(int i = mStart; i <= mEnd; i++){
				mResult += i;
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				if(mQuit) return;
			}
			mAfter.sendEmptyMessage(0);
		}
	}
}
